package string.ReverseStr;

/**
 * @ClassName ReverseStr
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-22 11:08
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class ReverseStr3 {
    /**
     * 翻转字符串里的单词
     * 给定一个字符串，逐个翻转字符串中的每个单词。
     * <p>
     * 示例 1：
     * 输入: "the sky is blue"
     * 输出: "blue is sky the"
     * <p>
     * 示例 2：
     * 输入: "  hello world!  "
     * 输出: "world! hello"
     * 解释: 输入字符串可以在前面或者后面包含多余的空格，但是反转后的字符不能包括。
     * <p>
     * 示例 3：
     * 输入: "a good   example"
     * 输出: "example good a"
     * 解释: 如果两个单词间有多余的空格，将反转后单词间的空格减少到只含一个。
     */

    public String reverseString(String str) {
        String trimStr = str.trim();

        String[] split = trimStr.split(" ");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = split.length - 1; i >= 0; i--) {
            if (!split[i].equals("")) {
                stringBuilder.append(split[i]);
                stringBuilder.append(" ");
            }
        }
        return stringBuilder.toString().trim();
    }

    public String reverseString1(String s) {

        StringBuilder stringBuilder = new StringBuilder();
        char[] newChars = s.trim().toCharArray();
        for (int i = newChars.length - 1; i >= 0; ) {
            StringBuilder tempStringBuilder = new StringBuilder("");
            while (i >= 0 && newChars[i] != ' ') {
                tempStringBuilder.append(newChars[i]);
                i--;
            }
            stringBuilder.append(reverse(tempStringBuilder.toString()));

            if (i != -1) {
                stringBuilder.append(" ");
            }

            while (i > 0 && newChars[i] == ' ') {
                i--;
            }
        }
        return stringBuilder.toString();

    }

    private String reverse(String s) {

        char[] chars = s.toCharArray();
        int i = 0, j = chars.length - 1;
        while (i < j) {
            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
            i++;j--;
        }

        return new String(chars);
    }


    public static void main(String[] args) {
        ReverseStr3 reverseStr3 = new ReverseStr3();

        String string = reverseStr3.reverseString1("  Bob    Loves  Alice   ");
        System.out.println(string);
    }
}